﻿using System;
using System.Collections.Generic;
using System.Web;
using MedicService.Domain;
using MedicService.Server.Exception;
using MedicService.Server.Factory;

namespace MedicService.Server.Utils {
    public class SessionUtils {


        public static void CheckTime(User user) {
            DateTime currentTime = DateTime.Now;
            TimeSpan timeSpan = currentTime.Subtract(user.LastActivity);
            if (timeSpan.TotalMinutes > 20) {
                throw new AutontificationException();
            }
        }

        public static void CheckRole(User user, string[] roles) {
            foreach (string role in roles) {
                if (user.Role == role) {
                    return;
                }
            }
            throw new AuthorizationException();
        }

        public static void CheckNull(Session session) {
            if (session == null) {
                throw new AutontificationException();
            }
        }

        public static void CheckAccess(Session session, params string[] roles) {
            CheckNull(session);
            var userFactory = new UserFactory();
            List<User> users = userFactory.GetList(session.SessionId);
            if (users.Count == 1) {
                User user = users[0];
                CheckTime(user);
                CheckRole(user, roles);
                user.LastActivity = DateTime.Now;
                try {
                    userFactory.Save(user);
                    return;
                } catch (System.Exception ex) {
                    throw new AuthorizationException();
                }
            }
            throw new AuthorizationException();
        }
    }
}